package com.quiz.bis.util.text;

import com.google.common.hash.Hashing;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class SimHash {
    private static final int HASH_BITS = 64;

    public static long computeSimHash(List<String> words) {
        int[] vector = new int[HASH_BITS];

        for (String word : words) {
            long wordHash = hash(word);
            for (int i = 0; i < HASH_BITS; i++) {
                long bitmask = 1L << i;
                if ((wordHash & bitmask) != 0) {
                    vector[i] += 1;
                } else {
                    vector[i] -= 1;
                }
            }
        }

        long fingerprint = 0;
        for (int i = 0; i < HASH_BITS; i++) {
            if (vector[i] > 0) {
                fingerprint |= (1L << i);
            }
        }

        return fingerprint;
    }

    private static long hash(String word) {
        // 简单的哈希函数实现
        return Hashing.murmur3_128().hashString(word, StandardCharsets.UTF_8).asLong();
    }

    public static int hammingDistance(long hash1, long hash2) {
        return Long.bitCount(hash1 ^ hash2);
    }
}
